<template>
  <div class="charts-container">
    <el-row :gutter="20" style="margin: 0 -10px;">
      <el-col v-for="(item, index) in scs" :key="index" :xs="24" :sm="12" :md="8" style="padding: 10px;">
        <el-card shadow="hover" class="chart-card">
          <div :id="`chart-${index}`" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import * as echarts from 'echarts';
import { ref, onMounted, nextTick } from 'vue';
import { useRoute } from 'vue-router';
import axios from 'axios';

const route = useRoute();
const id = route.query.id;
const scs = ref([]);

const getData = async () => {
  try {
    const response = await axios.get('http://localhost:8080/getMySC', {
      params: {
        id: id
      }
    });
    scs.value = response.data;
    console.log('Received data:', scs.value);
    // 确保DOM已更新再初始化图表
    await nextTick();
    initCharts();
  } catch (error) {
    console.error(error);
  }
};

// 初始化图表的函数
const initCharts = () => {
  if (!scs.value.length) return;

  // 检查页面是否已经加载完成
  if (document.readyState === 'complete') {
    initializeCharts();
  } else {
    window.addEventListener('load', initializeCharts);
  }
};

// 实际初始化图表的逻辑
const initializeCharts = () => {
  console.log('Charts initialized');
  scs.value.forEach((item, index) => {
    const chartDiv = document.getElementById(`chart-${index}`);
    chartDiv.style.width = '300px';
    chartDiv.style.height = '300px';
    if (!chartDiv) return;

    const chart = echarts.init(chartDiv);
    const singleOption = {
      title: {
        text: `${item.cname}`,
        left: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'bold'
        }
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        data: ['出勤', '缺勤']
      },
      series: [
        {
          name: 'Data',
          type: 'pie',
          radius: '50%',
          center: ['50%', '50%'],
          label: {
            show: true,
            position: 'outside',
            formatter: '{b}: {c} ({d}%)'
          },
          data: [
            { value: item.attendance || 0, name: '出勤' },
            { value: (1 - (item.attendance || 0)).toFixed(2), name: '缺勤' }
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    };
    chart.setOption(singleOption);
  });
};

// 在组件挂载后获取数据
onMounted(getData);
</script>

<style scoped>
.charts-container {
  padding: 20px;
}

.chart-card {
  height: 300px; /* 确保有明确的高度 */
  display: flex;
  justify-content: center;
  align-items: center;
  transition: all 0.3s;
}

.chart {
  width: 100%;
  height: 100%;
}
</style>